<template>
  <div class="app-container">
    <div class="container-main">
      <div class="container-project">
        <div class="head-container">
          <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 10px;">
            <div v-if="queryParams.type == 'flow'" style="font-weight: bold;color: #444;">流程列表</div>
            <div v-if="queryParams.type == 'project'" style="font-weight: bold;color: #444;">项目列表</div>
            <!-- <div>
              <el-button class="add-project" type="primary">+</el-button>
            </div> -->
          </div>
        </div>
        <div class="head-container">
          <el-input v-model="queryParamsNode.name" @keyup.enter.native="handleQueryProject" placeholder="请输入名称"
            clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <div v-for="item in projectsList" :key="item.id" :class="item.id == project.id ? 'project-item-active' : ''"
            class="project-item" @click="handleProjectClick(item)">
            <div class="project-item-name">
              <div>{{ item.name }}</div>
              <div v-if="queryParams.type == 'flow'" class="project-item-type-0">模板</div>
              <div v-if="queryParams.type == 'project'" class="project-item-type-1">项目</div>
            </div>
            <div class="project-item-description">
              {{ item.description }}
            </div>
            <div class="project-item-create">
              <div><i class="el-icon-user"></i>{{ item.createBy }}</div>
              <div><i class="el-icon-date"></i>{{ item.createTime }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="container-node">
        <div v-if="nodesList.length == 0 && project.id > 0 " class="content-container">
          <el-button class="add-node" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['business:nodes:add']">创建节点</el-button>
        </div>
        <div v-if="nodesList.length > 0" class="content-container2">
          <el-timeline style="margin-top: 20px;">
            <el-timeline-item timestamp="" v-for="item in nodesList" :key="item.id" placement="bottom">
              <el-card :class="node.id == item.id ? 'node-card-active': '' ">
                <div :class="node.id > 0 ? '': 'node-card'">
                  <div>
                    <h4>{{ item.name }}</h4>
                    <p>{{ item.description }}</p>
                  </div>
                  <div>
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="handleSetting(item)"
                      v-hasPermi="['business:nodes:add']">配置</el-button>
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd(item)"
                      v-hasPermi="['business:nodes:add']">新增</el-button>
                    <el-button type="success" icon="el-icon-edit" size="mini" @click="handleUpdate(item)"
                      v-hasPermi="['business:nodes:edit']">修改</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(item)"
                      v-hasPermi="['business:nodes:remove']">删除</el-button>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <transition name="el-zoom-in-right">
        <div v-show="this.node.id > 0" class="container-node-files">
          <div style="display: flex;justify-content: space-between;padding: 20px 0px;">
            <div>
              <el-divider direction="vertical" style="width: 5px; background-color: #1890ff;"></el-divider>
              <span style="font-weight: 600;font-size: 16px;">节点信息</span>
            </div>
            <div style="font-size: 18px;cursor: pointer;" @click="node = {}">x</div>
          </div>

          <div class="container-node-item">
            <!-- <div class="container-node-item-title">负责人</div> -->
            <el-divider content-position="left">负责人</el-divider>
            <div class="container-node-item-content">
              <el-cascader :show-all-levels="false" v-model="projectDept" :options="deptOptions" :props="defaultProps"
                placeholder="部门" clearable style="width: 200px;" @change="handleChange"></el-cascader>

              <el-select v-model="node.principalId" filterable placeholder="请选择" @change="handleChangeUser"
                style="width: 200px;">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </div>
          </div>

          <div class="container-node-item">
            <!-- <div class="container-node-item-title">预计周期</div> -->
            <el-divider content-position="left">预计周期</el-divider>
            <div class="container-node-item-content">
              <el-date-picker v-model="projectDate" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" @change="handleChangeDate">
              </el-date-picker>
            </div>
          </div>

          <div class="container-node-item">
            <el-divider class="container-node-item-title" content-position="left">文件信息</el-divider>
            <div class="container-node-item-files">
              <!-- <el-button class="add-node" type="primary" icon="el-icon-plus" size="mini" @click="handleAddFile"
                  v-hasPermi="['business:files:add']">添加文件</el-button> -->
              <el-button style="margin-bottom: 15px;" type="primary" icon="el-icon-plus" size="mini"
                @click="handleAddFile" v-hasPermi="['business:files:add']">新增</el-button>

              <el-table v-loading="loading" :data="fileList" border>
                <el-table-column label="文件名称" align="left" prop="fileName" />
                <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateFile(scope.row)"
                      v-hasPermi="['business:files:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteFile(scope.row)"
                      v-hasPermi="['business:files:remove']">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <pagination v-show="fileTotal>0" :total="fileTotal" :page.sync="queryParamsFile.pageNum"
                :limit.sync="queryParamsFile.pageSize" @pagination="getFileList" />
            </div>
          </div>
        </div>
      </transition>

    </div>
    <!-- 添加或修改项目节点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="所属项目" prop="projectsId">
            <el-input v-model="form.projectsId" placeholder="请输入所属项目" />
          </el-form-item>
          <el-form-item label="父节点ID" prop="parentId">
            <el-input v-model="form.parentId" placeholder="请输入父节点ID" />
          </el-form-item> -->
        <el-form-item label="节点名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入节点名称" />
        </el-form-item>
        <el-form-item label="解释介绍" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改文件列表对话框 -->
    <el-dialog title="节点文件" :visible.sync="openformFile" width="500px" append-to-body>
      <el-form ref="formFile" :model="formFile" :rules="formFileRules" label-width="80px">

        <el-form-item label="名称" prop="fileName">
          <el-input v-model="formFile.fileName" placeholder="请输入文件名称" />
        </el-form-item>

        <el-form-item label="文件" prop="">
          <file-upload v-model="formFile.filePath" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formFile.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelFile">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listNodes,
    listAllNodes,
    getNodes,
    delNodes,
    addNodes,
    updateNodes
  } from "@/api/business/nodes";
  import {
    listProjects
  } from "@/api/business/projects";
  import {
    listFlow
  } from "@/api/business/flow";
  import {
    deptUserTreeSelect,
    deptTreeSelect,
    listUser
  } from "@/api/system/user";
  import {
    listFiles,
    getFiles,
    delFiles,
    addFiles,
    updateFiles
  } from "@/api/business/files";
  export default {
    name: "Nodes",
    watch: {
      // 监听整个路由对象变化
      $route(to, from) {
        // 当路由变化时执行逻辑
        console.log('路由变化:', to.params, to.query);
        if (to.query.id) {
          this.queryParams.projectsId = to.query.id;
        }
        if (to.query.type) {
          this.queryParams.type = to.query.type;
        }
        if (this.queryParams.type == 'flow') {
          this.getlistFlowList();
        } else {
          this.getProjectsList();
        }
        this.getList();
      },
      // 监听查询参数（如 keyword）
      // '$route.query.id'(newId) {
      //   console.log('搜索关键字变化:', newId);
      //   this.queryParams.projectsId = newId;
      //   this.getList();
      // },
      // '$route.query.type'(newId) {
      //   console.log('搜索关键字变化:', newId);
      //   this.queryParams.type = newId;
      //   this.getList();
      // },


    },
    data() {
      return {
        projectsName: '',
        // 根路径
        baseURL: process.env.VUE_APP_BASE_API,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        fileTotal: 0,
        // 项目节点表格数据
        projectsList: [],
        nodesList: [],
        fileList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 部门树选项
        deptOptions: undefined,
        defaultProps: {
          children: "children",
          label: "label",
          value: 'id'
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          projectsId: null,
          parentId: null,
          name: null,
          description: null,
          remark: null,
        },
        // 查询参数
        queryParamsNode: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          type: null,
          description: null,
          remark: null,
        },
        queryParamsFile: {
          pageNum: 1,
          pageSize: 10,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          id: [{
            required: true,
            message: "$comment不能为空",
            trigger: "blur"
          }],
          projectsId: [{
            required: true,
            message: "所属项目不能为空",
            trigger: "blur"
          }],
          parentId: [{
            required: true,
            message: "父节点ID不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "节点名称不能为空",
            trigger: "blur"
          }],
          description: [{
            required: true,
            message: "解释介绍不能为空",
            trigger: "blur"
          }]
        },
        project: {},
        node: {},
        userList: [],
        principal: {},
        projectDate: [],
        projectDept: [],
        openformFile: false,
        formFile: {},
        formFileRules: {
          fileName: [{
            required: true,
            message: "文件名称不能为空",
            trigger: "blur"
          }],
        },
      };
    },
    created() {
      this.queryParams.projectsId = this.$route.query.id;
      this.queryParams.type = this.$route.query.type;
      if (this.queryParams.type == 'flow') {
        this.getlistFlowList();
      } else {
        this.getProjectsList();
      }
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
      this.getList();
    },
    methods: {
      handleQueryProject() {
        this.nodesList = [];
        this.project = {};
        if (this.queryParams.type == 'flow') {
          this.getlistFlowList();
        } else {
          this.getProjectsList();
        }
      },
      getProjectsList() {
        this.loading = true;
        listProjects(this.queryParamsNode).then(response => {
          this.projectsList = response.rows;
          for (let i = 0; i < this.projectsList.length; i++) {
            if (this.projectsList[i].id == this.queryParams.projectsId) {
              this.handleProjectClick(this.projectsList[i])
            }
          }
        });
      },
      getlistFlowList() {
        this.loading = true;
        listFlow(this.queryParamsNode).then(response => {
          this.projectsList = response.rows;
          for (let i = 0; i < this.projectsList.length; i++) {
            if (this.projectsList[i].id == this.queryParams.projectsId) {
              this.handleProjectClick(this.projectsList[i])
            }
          }
        });
      },
      /** 查询项目节点列表 */
      getList() {
        this.loading = true;
        listAllNodes(this.queryParams).then(response => {
          this.nodesList = response.data
          // this.nodesList = response.rows;
          // this.total = response.total;
          this.loading = false;
        });
      },
      handleProjectClick(item) {
        this.queryParams.projectsId = item.id;
        this.getList();
        this.project = item;
        this.node = {};
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          description: null,
          remark: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id;
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd(item) {
        this.reset();
        this.open = true;
        this.title = "添加节点";
        if (item) {
          this.form.from = item.id;
          this.form.to = item.to;
          this.form.projectsId = item.projectsId;
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getNodes(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改项目节点";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.form.projectsId = this.queryParams.projectsId
        this.form.type = this.queryParams.type
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateNodes(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addNodes(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除项目节点数据项？').then(function () {
          return delNodes(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleSetting(row) {
        this.node = row;
        if (this.node.deptId) {
          this.getUserList();
          this.projectDept = [1, this.node.deptId];
        } else {
          this.projectDept = [];
        }
        if (this.node.startDate) {
          this.projectDate = [this.node.startDate, this.node.endDate]
        } else {
          this.projectDate = [];
        }
        this.queryParamsFile.nodeId = this.node.id
        this.handleQuery();
      },
      handleChange(value) {
        console.log(value);
        this.userList = [];
        this.node.principalId = null;
        this.node.deptId = null;
        if (value && value.length > 0) {
          this.node.deptId = value[value.length - 1];
          this.getUserList();
        }
        updateNodes(this.node).then(response => {})
      },
      handleChangeUser(value) {
        // console.log(this.node);
        updateNodes(this.node).then(response => {})
      },
      handleChangeDate(value) {
        console.log(this.projectDate);
        this.node.startDate = value[0];
        this.node.endDate = value[1];
        // console.log(this.node);
        updateNodes(this.node).then(response => {})
      },
      getUserList() {
        listUser({
          pageNum: 1,
          pageSize: 100,
          deptId: this.node.deptId
        }).then(response => {
          this.userList = response.rows;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParamsFile.pageNum = 1;
        this.getFileList();
      },
      getFileList() {
        listFiles(this.queryParamsFile).then(response => {
          this.fileList = response.rows
          this.fileTotal = response.total
        })
      },
      handleAddFile() {
        this.formFile = {
          id: null,
          fileName: null,
          filePath: null,
        };
        this.resetForm("formFile");
        this.openformFile = true;
      },
      handleUpdateFile(row) {
        this.formFile = {
          id: row.id,
          fileName: row.fileName,
          filePath: row.filePath,
        };
        this.openformFile = true;
      },
      handleDeleteFile(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除文件列表数据项？').then(function () {
          return delFiles(ids);
        }).then(() => {
          this.getFileList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      cancelFile() {
        this.formFile = {
          id: null,
          fileName: null,
          filePath: null,
        };
        this.resetForm("formFile");
        this.openformFile = false;
      },
      submitFileForm() {
        this.$refs["formFile"].validate(valid => {
          if (valid) {
            this.formFile.nodeId = this.node.id;
            if (this.formFile.id != null) {
              updateFiles(this.formFile).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.openformFile = false;
                this.getFileList();
              });
            } else {
              addFiles(this.formFile).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.openformFile = false;
                this.getFileList();
              });
            }
          }
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/nodes/export', {
          ...this.queryParams
        }, `nodes_${new Date().getTime()}.xlsx`)
      }
    }
  };

</script>
<style scoped>
  .app-container {
    margin: 0px 0px;
    padding: 0 0;
    min-height: calc(100vh - 124px);
    background-color: #f2f3f5;
  }

  .container-main {
    display: flex;
  }

  .container-project {
    min-height: calc(100vh - 104px);
    background-color: #FFF;
    width: 300px;
    border-right: 1px solid #e5e7eb;
    padding: 20px;
  }

  .head-container {
    padding: 1px;
  }

  .project-item {
    margin-top: 10px;
    border-radius: 0.5rem;
    --tw-bg-opacity: 1;
    background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1));
    padding: 1rem;
    --tw-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    --tw-shadow-colored: 0 4px 16px var(--tw-shadow-color);
    box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
    transition-property: all;
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    transition-duration: 300ms;
  }

  .project-item:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .project-item-active {
    border: 2px solid #165dff;
  }

  .project-item-name {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
  }

  .project-item-type-0 {
    font-size: 12px;
    color: #FF7D00;
    background-color: #ff7d001a;
    padding: 5px 10px;
    border-radius: 5px;
  }

  .project-item-type-1 {
    font-size: 12px;
    color: #165dff;
    background-color: #165dff1a;
    padding: 5px 10px;
    border-radius: 5px;
  }

  .project-item-description {
    font-size: 12px;
    color: #6b7280;
    margin: 8px 0px 8px;
  }

  .project-item-create {
    font-size: 12px;
    color: #6b7280;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
  }

  .container-node {
    background-color: #FFF;
    flex: 1;
    height: calc(100vh - 104px);
    overflow-y: auto;
  }

  .container-node-files {
    border-left: 1px solid #e5e7eb;
    background-color: #FFF;
    flex: 1;
    padding: 0px 20px;
    /* transition: all 3s ease; */
    height: calc(100vh - 104px);
    overflow-y: auto;
  }

  ::v-deep .el-timeline-item__wrapper {
    transition: all 0.3s ease;
  }

  ::v-deep .el-timeline-item__wrapper:hover {
    transform: scale(1.03);
    margin-left: 18px;
  }

  ::v-deep .el-scrollbar__wrap {
    margin: 0 0 !important;
  }

  .node-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .node-card-active {
    transform: scale(1.03);
    margin-left: 18px;
    border: 1px solid #156ffd;
  }

  .content-container {
    /* transform: translate(-50%, -50%); */
    text-align: center;
    line-height: calc((100vh - 180px));
  }

  .content-container2 {
    padding: 20px 60px 20px 20px;
  }

  .add-node {
    width: 150px;
    height: 60px;
    font-size: 14px;
  }

  .add-project {
    background: #165dff;
    font-size: 27px;
    width: 30px;
    height: 40px;
    line-height: 20px;
    padding-left: 6px;
    border-radius: 2px !important;

  }

  .el-divider--vertical {
    width: 5px;
    background-color: #156ffd;
  }

  .container-node-item {
    margin-top: 10px;
  }

  .el-divider__text {
    color: #888;
    font-weight: 600;
    font-size: 13px;
  }

  .container-node-item-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
  }

</style>
